let tasks = JSON.parse(localStorage.getItem("tasks")) || [];

function saveTasks() {
  localStorage.setItem("tasks", JSON.stringify(tasks));
}

function renderTasks() {
  const list = document.getElementById("task-list");
  list.innerHTML = "";

  tasks.forEach((task, index) => {
    const li = document.createElement("li");
    li.className = task.completed ? "completed" : "";
    li.innerHTML = `
      <span onclick="toggleTask(${index})">${task.title}</span>
      <div class="task-actions">
        <button onclick="deleteTask(${index})">🗑</button>
      </div>
    `;
    list.appendChild(li);
  });

  document.getElementById("total-count").textContent = tasks.length;
  document.getElementById("done-count").textContent = tasks.filter(t => t.completed).length;
}

function addTask() {
  const input = document.getElementById("task-input");
  const title = input.value.trim();
  if (!title) return;
  tasks.push({ title, completed: false });
  input.value = "";
  saveTasks();
  renderTasks();
}

function toggleTask(index) {
  tasks[index].completed = !tasks[index].completed;
  saveTasks();
  renderTasks();
}

function deleteTask(index) {
  tasks.splice(index, 1);
  saveTasks();
  renderTasks();
}

window.onload = renderTasks;
